package com.example.usermanagement.repository;

import com.example.usermanagement.model.ERole;
import com.example.usermanagement.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;

@Repository
public interface UserRepository extends JpaRepository<User, Long> {

    Optional<User> findByUsername(String username);

    Boolean existsByUsername(String username);

    Boolean existsByEmail(String email);
    
    /**
     * 根据搜索关键词和角色筛选用户
     * 此方法在数据库层面进行过滤，提高性能并减少内存消耗
     */
    @Query("SELECT u FROM User u JOIN u.roles r WHERE (:searchQuery IS NULL OR u.username LIKE %:searchQuery% OR u.email LIKE %:searchQuery% OR u.firstName LIKE %:searchQuery% OR u.lastName LIKE %:searchQuery%) AND (:roleFilter IS NULL OR r.name = :roleFilter)")
    List<User> findBySearchQueryAndRole(@Param("searchQuery") String searchQuery, 
                                        @Param("roleFilter") ERole roleFilter);

}